
using Autofac.Core;
using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Hosting;
using NLog;
using NLog.Web;
using NLog.Extensions.Logging;
using 微信机器人服务.Services;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.Quartz;
using Autofac;
using System.Collections.Specialized;
using 微信机器人服务.Quartz;
using WeChatBotSDK.Extensions;
using SqlSugar;
using System.Diagnostics;
using 微信机器人服务.Service;
using 微信机器人服务.Quartz.Jobs;

namespace 微信机器人服务
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var log = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
            log.Info("启动");

            try
            {
                var options = new WebApplicationOptions
                {
                    Args = args,
                    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
                };
                var builder = WebApplication.CreateBuilder(options);

                builder.Services.AddLogging(loggingBuilder =>
                {
                    loggingBuilder.ClearProviders();
                    loggingBuilder.AddNLog();
                });
                builder.Services.AddSingleton<ISqlSugarClient>(e =>
                {
                    SqlSugarScope Db = new SqlSugarScope([
                           new ConnectionConfig
                        {
                            DbType = SqlSugar.DbType.Sqlite, // 设置数据库类型
                            ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"), 
                            IsAutoCloseConnection = true, // 是否自动关闭连接
                            ConfigId = "log"
                        }
                           ]
#if DEBUG
                              , db =>
                              {
                                  db.Aop.OnLogExecuting = (sql, p) =>
                                  {
                                      //Debug.WriteLine(sql);
                                      Debug.WriteLine(UtilMethods.GetSqlString(DbType.Sqlite, sql, p));
                                  };

                                  //如果是 日志库 不要加AOP防止AOP循环引用
                              }
#endif
                              );
                    return Db;
                });
                builder.Services.AddSingleton<DatabaseInitializer>();
                builder.Services.AddHostedService<StartSystemJob>();
                //Quartz注入
                builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureContainer<ContainerBuilder>(builder =>
                    {
                        var schedulerConfig = new NameValueCollection {
      {"quartz.threadPool.threadCount", "10"},
      // {"quartz.threadPool.threadNamePrefix", "MyScheduleWorker"} comment this in Quartz version 3+,
      {"quartz.scheduler.threadName", "MyScheduler"}
                     };

                        builder.RegisterModule(new QuartzAutofacFactoryModule
                        {
                            ConfigurationProvider = c => schedulerConfig
                        });
                        var assembly = typeof(推送任务).Assembly;
                        builder.RegisterModule(new QuartzAutofacJobsModule(assembly));
                        builder.RegisterType<QuartzJobsFactory>().As<IQuartzJobsFactory>();
                    });

                // Add services to the container.

                builder.Services.AddControllers().AddWeChatMessageHandlers();
                builder.Services.AddQXWeChatBot("http://123.230.63.98:8888");//微信机器人服务
                builder.Services.AddWeChatBot("http://123.230.63.98:8889");//微信机器人服务
                // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
                builder.Services.AddEndpointsApiExplorer();
                builder.Services.AddSwaggerGen();

                var app = builder.Build();

                // Configure the HTTP request pipeline.
                if (app.Environment.IsDevelopment())
                {
                    app.UseSwagger();
                    app.UseSwaggerUI();
                }

                app.UseAuthorization();


                app.MapControllers();

                app.Run();
            }
            catch (Exception e)
            {
                log.Error(e, "程序启动时出现异常");
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }

        }
    }
}
